package com.gmail.bloim.serg.acmbuilder;

import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: Администратор
 * Date: 26.04.13
 * Time: 12:43
 */
public class JavaFile {
    private final File source;
    private Pattern packagePattern = Pattern.compile("package\\s+([\\w\\d_\\.]+);");
    private String filePackage = null;
    private Pattern importPattern = Pattern.compile("import(?:\\s+static)?\\s+([\\w\\d_\\.]+)\\s*;");
    private Set<Import> fileImports = new HashSet<Import>();
    private String content;

    public JavaFile(String path) {
        this(new File(path));
    }

    public JavaFile(File file) {
        source = file;
    }

    public void parse() throws IOException {
        InputStream is = new FileInputStream(source);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        parsePackage(reader);
        parseImports(reader);
        parseBody(reader);
    }

    private void parseBody(BufferedReader reader) throws IOException {
        content = IOUtils.toString(reader);
    }

    private int parseImports(BufferedReader reader) throws IOException {
        while (true) {
            String importStr = scanForPattern(reader, importPattern);
            if (importStr == null)
                break;
            Matcher matcher = importPattern.matcher(importStr.trim());
            matcher.matches();
            String className = matcher.group(1);
            fileImports.add(new Import(importStr, className));
        }
        return fileImports.size();
    }

    private void parsePackage(BufferedReader reader) throws IOException {
        String packStr = scanForPattern(reader, packagePattern);
        if (packStr == null)
            filePackage = null;
        Matcher matcher = packagePattern.matcher(packStr.trim());
        matcher.matches();
        filePackage = matcher.group(1);
    }

    private String scanForPattern(BufferedReader reader, Pattern packagePattern1) throws IOException {
        String line = "";
        do {
            reader.mark(500);
            line = reader.readLine();
            if (line == null)
                return null;
            String trimmed = line.trim();
            if ("".equals(trimmed))
                continue;
            Matcher matcher = packagePattern1.matcher(trimmed);
            if (matcher.matches()) {
                return line;
            } else {
                reader.reset();
                break;
            }
        } while (line != null);
        return null;
    }

    public String getFilePackage() {
        return filePackage;
    }

    public Set<Import> getFileImports() {
        return fileImports;
    }

    public String getContent() {
        return content;
    }
}
